#pragma once

#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <signal.h>
#include <fcntl.h>
#include <cstdlib>
#include <cstring>
#include "err.hpp"
#include "log.hpp"

void Daemon()
{
    signal(SIGPIPE, SIG_IGN);
    signal(SIGCHLD, SIG_IGN);

    if (fork() > 0) exit(0);

    pid_t ret = setsid();
    if (ret == -1)
    {
        logMessage(FATAL, "daemon error, code:%d, string:%s", errno, strerror(errno));
        exit(DAEMON_ERR);
    }

    int fd = open("/dev/null", O_RDWR);
    if (fd < 0)
    {
        logMessage(FATAL, "open error, code:%d, string:%s", errno, strerror(errno));
    }
    dup2(fd, 0);
    dup2(fd, 1);
    dup2(fd, 2);
    close(fd);
}